import { createStore } from 'vuex'
import { getKeMu, getDeptByKeMu, login, getSubjectByDept } from '@/api/index.js'
const store = createStore({
	state:{
		token: uni.getStorageSync('token') || '',
		openid: uni.getStorageSync('openid') || '',
		loginInfo: uni.getStorageSync('loginTime')=='' || uni.getStorageSync('loginTime')>new Date().getTime()-24*60*60*1000*7 ? uni.getStorageSync('loginInfo') : '',
		deviceInfo: {},//设备基础信息
		KEMULIST: [],//科目列表
		keMuIndex: uni.getStorageSync('keMuIndex') || [],
		DEPTBYKEMULIST: [],//分类列表
		SUBJECTBYDEPT: [],//题目列表
		PROVIDER: '',//服务供应商
		questionDefaultTab: '',//question页面分类导航默认选中项
		barInfo: {},//自定义标题位置
		uuid: '',
		question: [],//2首页题库选择项
		exerciseList: [],//做题答案list
		patternList: [],//做题的模式list
		subjectCommentStatusList: [],//每道题的收藏和笔记状态
		sheetIndex: 0,//答题卡返回刷题进行定位
		exerciseTime: 0,//答题时间
		exercisePattern: uni.getStorageSync('exercisePattern') || 1,//'练习模式','快速模式','背题模式','快考模式'
		examObj: [],//当前题信息
		isAI: false,//是否ai生成的题
		isAIType: '',//ai生成的题 '1': '错题攻克','2': '章节强化','3': '每日提升','4': '万人模拟考',
		isError: false,//是否是错题列表进入
		mrtsKeMu: uni.getStorageSync('mrtsKeMu') || '',//每日提升是否首次进入
		homeDataUpdata: false,//首页数据是否要刷新
		sheetTitle: [],//答题卡页面标题内容
		fontSizeScale: uni.getStorageSync('fontSizeScale') || 1,//字体缩放比例
		exReadonly: false,//答题页是否只读
		noticeDetail: {},
		DEVICEINFO: {},//设备信息
	},
	mutations: {
		set(state,company){
			state[company[0]]=company[1]
		},
		updateToken(state,token){//存token
			state.token=token;
			uni.setStorageSync('token',token);
		},
		updateOpenid(state,openid){//存openid
			state.openid=openid;
			uni.setStorageSync('openid',openid);
		},
		updateLoginInfo(state,info){//存用户登录信息
			state.loginInfo=info;
			console.log(info,'info---')
			uni.setStorageSync('loginInfo',info);
			uni.setStorageSync('loginTime',new Date().getTime());
		},
		subjectByDeptUpdata(state,res){
			state.SUBJECTBYDEPT=res.data;
			state.exerciseList=new Array(res.data?.length);
			state.patternList=new Array(res.data?.length);
			state.subjectCommentStatusList=new Array(res.data?.length);
		},
	},
	actions: {
		async getKeMu({ state, commit, dispatch }) {
		    try {
				const res = await getKeMu();
				res.data=res.data.map(item=>{
					if(['护士资格','初级护师'].includes(item.n)){
						item.s=[]
					}
					return item
				})
				commit('set', ['KEMULIST', res.data]);
				if(state.keMuIndex.length<=0) return res.data;
				dispatch('getDeptByKeMu');
				return res.data
		    } catch (error) {
				uni.showToast({title: '获取科目失败',icon: 'none'});
				return []
		    }
	    },
		async getDeptByKeMu({ commit, getters }) {
			try {
				const keyP=getters.getKeMuParams;
				const params={
					keMu1: keyP.kemu1,
				}
				if(keyP.kemu2){
					params.keMu2=keyP.kemu2
				}
				const res = await getDeptByKeMu(params);
				commit('set', ['DEPTBYKEMULIST', res.data]);
				return res.data
			} catch (error) {
				uni.showToast({title: '获取分类失败',icon: 'none'});
				return []
			}
		},
		async getSubjectByDept({ state, commit, getters }) {
			commit('subjectByDeptUpdata',[]);
			try {
				const list=state.DEPTBYKEMULIST;
				const key=state.question;
				const item=list[key[0]]?.s[key[1]];
				const res = await getSubjectByDept({pid2: item.v,pid3: item.s[key[2]].v});
				commit('subjectByDeptUpdata',res);
				return res.data
			} catch (error) {
				uni.showToast({title: '获取题目失败',icon: 'none'});
				return []
			}
		},
		async getProvider({ state, commit, dispatch }) {
		    try {
				// #ifdef MP-WEIXIN
				uni.getProvider({
					service: 'oauth',
					success: (res)=>{
						if(res.provider){
							commit('set', ['PROVIDER',res.provider[0]]);
							console.log(dispatch,'---66')
							dispatch('userLogin');
						}
					}
				});
				// #endif
				// #ifndef MP-WEIXIN
				if(!state.loginInfo.phone){
					uni.reLaunch({ url: '/pagesB/login/login' })
				}
				// #endif
		    } catch (error) {
				uni.showToast({title: '获取服务供应商失败',icon: 'none'});
				return ''
		    }
	    },
		async userLogin({ state, commit, dispatch, getters }) {
			try {
				uni.login({
					provider: state.PROVIDER, //使用微信登录
					success: (res)=> {
						console.log(state.PROVIDER,'provider');
						console.log(res,'res');
						login({code: res.code}).then(res=>{
							if(res?.data?.token){
								commit('updateToken', res?.data?.token);
							}else if(res?.data?.openid){
								commit('set', ['loginInfo','']);
								commit('set', ['token','']);
							}
							if(res?.data?.openid){
								commit('updateOpenid', res?.data?.openid);
							}
							if(res?.data?.user){
								if(!res?.data?.openid){
									commit('set', ['openid','']);
								}
								commit('updateLoginInfo', res?.data?.user);
								dispatch('getKeMu');
							}
						})
					},
					fail: (res)=>{
						console.log(res,'-------error-36')
					}
				})
			} catch (error) {
				uni.showToast({title: '登录失败',icon: 'none'});
				return []
			}
		},
	},
	getters: {//store的计算属性
		getKeMuName: (state) => {
			if(!(state.KEMULIST.length>0))return '';
			const item=state.KEMULIST[state.keMuIndex[0]];
			if(state.keMuIndex.length==1){
				return item.v
			}else{
				return item?.s[state.keMuIndex[1]]?.v
			}
	    },
		getKeMuId: (state) => {
			if(state.KEMULIST.length<=0)return '';
			const item=state.KEMULIST[state.keMuIndex[0]];
			if(state.keMuIndex.length==1){
				return [item?.n]
			}else{
				return [item?.n, item?.s[state.keMuIndex[1]].n]
			}
	    },
		getKeMuItem: (state) => {
			if(!(state.KEMULIST.length>0))return '';
			const item=state.KEMULIST[state.keMuIndex[0]];
			if(state.keMuIndex.length==1){
				return item
			}else{
				return item?.s[state.keMuIndex[1]]
			}
	    },
		getKeMuParams: (state, getters) => {
			const id=getters.getKeMuId;
			let params={
				kemu1: id[0],
				kemu2: id[1],
			}
			!id[1] && (delete params.kemu2)
			return params
		},
	}
})

export default store